package com.cskaoyan.market.controller;

import com.cskaoyan.market.service.MarketAdminService;
import com.cskaoyan.market.service.MarketAdminServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/admin/profile/*")
public class AdminProfileController extends HttpServlet {
    MarketAdminService marketAdminService =new MarketAdminServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String op = req.getRequestURI().replace(req.getContextPath() + "/admin/profile/","" );
        if("password".equals(op)){
            changePassword(req,resp);
        }
    }
    private void changePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        String newPassword = JacksonUtil.parseString(requestBody, "newPassword");
        String newPassword2 = JacksonUtil.parseString(requestBody, "newPassword2");
        String oldPassword = JacksonUtil.parseString(requestBody, "oldPassword");
        if(!Objects.equals(newPassword2, newPassword)){
            Object failed = ResponseUtil.fail(600, "两次密码不一致");
            resp.getWriter().write(JacksonUtil.writeValueAsString(failed));
            return;
        }
        boolean updateFlag = marketAdminService.updatePassword(newPassword, oldPassword);
        if(updateFlag){
            HttpSession session = req.getSession();
            if (session != null) {
                session.removeAttribute("admin");
            }
            Object ok = ResponseUtil.ok();
            resp.getWriter().write(JacksonUtil.writeValueAsString(ok));
            
        }else {
            Object failed = ResponseUtil.fail(600, "旧密码错误");
            resp.getWriter().write(JacksonUtil.writeValueAsString(failed));
        }
    }
}
